import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const isLoggedIn = ref(false)
  const userInfo = ref({
    username: '',
    token: ''
  })

  // 登录
  const login = async (loginData) => {
    try {
      // 这里应该调用真实的API
      // const response = await api.login(loginData)
      
      // 模拟登录成功
      if (loginData.username && loginData.password) {
        userInfo.value = {
          username: loginData.username,
          token: 'mock_token_' + Date.now()
        }
        isLoggedIn.value = true
        
        // 保存到本地存储
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        localStorage.setItem('isLoggedIn', 'true')
        
        ElMessage.success('登录成功！')
        return true
      } else {
        ElMessage.error('请输入用户名和密码')
        return false
      }
    } catch (error) {
      ElMessage.error('登录失败：' + error.message)
      return false
    }
  }

  // 登出
  const logout = () => {
    isLoggedIn.value = false
    userInfo.value = {
      username: '',
      token: ''
    }
    
    // 清除本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('isLoggedIn')
    
    ElMessage.success('已退出登录')
    router.push('/login')
  }

  // 检查认证状态
  const checkAuth = () => {
    const storedUserInfo = localStorage.getItem('userInfo')
    const storedLoginStatus = localStorage.getItem('isLoggedIn')
    
    if (storedUserInfo && storedLoginStatus === 'true') {
      userInfo.value = JSON.parse(storedUserInfo)
      isLoggedIn.value = true
    }
  }

  return {
    isLoggedIn,
    userInfo,
    login,
    logout,
    checkAuth
  }
})
